<template>
  <CPageTable
    class="product-bom-drawer-page-table"
    @register="registerPage"
    v-model:searchForm="searchForm"
    v-loading="loading"
  >
    <vxe-column
      show-overflow="tooltip"
      field="nodeName"
      :minWidth="300"
      title="物料名称/物料编码"
      :filters="nodeNameFilterOptions"
      :filter-method="filterAgeMethod"
      tree-node
    >
      <template #default="scope">
        <CTableColumn
          :main-text="scope.row.nodeName"
          :sub-text="scope.row.nodeCode"
          :color="isFilter && scope.row.filtered ? '#03AC82' : ''"
        ></CTableColumn>
      </template>
    </vxe-column>
    <template #dosageSlot="{ scope }">
      {{
        scope.row.unit == 'pcs' ? 'pcs' : scope.row.dosage ? scope.row.dosage + scope.row.unit : '-'
      }}
    </template>
    <template #supplierSlot="{ scope }">
      <CTableColumn
        :main-text="scope.row?.supplierName"
        :sub-text="scope.row?.supplierCode"
      ></CTableColumn>
    </template>
    <template #syncStatusSlot="{ scope }">
      <el-tag :type="renderTag(scope.row.syncStatus)" v-if="scope.row.syncStatus">
        {{ BomSyncStatusMap[scope.row.syncStatus as keyof typeof BomSyncStatusEnum] }}
      </el-tag>
      <span v-else>-</span>
    </template>
    <template #op="{ scope }">
      <el-button
        type="primary"
        text
        @click="handleSyncFirstPart(scope.row)"
        v-if="scope.row.parentNodeNo === '-1'"
        >同步</el-button
      >
    </template>
  </CPageTable>
</template>

<script lang="ts" setup name="ModelDetailDrawerLayout">
import { computed, ref, nextTick, reactive } from 'vue';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';
import { CTableColumn } from '@/components/CTable';
import { BomSyncStatusEnum, BomSyncStatusMap } from '@/constants/enum';
import {
  CPageTable,
  useCPageTable,
  SearchOptionsType,
  TableFieldsSettingType,
  CPageTableProps
} from '@/components/CPageTable';
import { getBomProductTree, postSyncFirstPart } from '@/apis/system/config/bomProduct';
import type { GetBomProductTreeResult } from '@/apis/system/config/model/bomProductModel';
import { useRoute } from 'vue-router';
import { useMessage } from '@/hooks/useMessage';

const route = useRoute();
const productNo = route.query.productNo as string;
const title = route.query.title as string;

const loading = ref(false);
const { createMessage, createConfirm } = useMessage();
const searchOptions: SearchOptionsType[] = [
  {
    name: '物料编码或名称',
    field: 'searchName',
    type: 'input',
    onSearchFormChange: (form: any) => {
      console.log('onSearchFormChange 物料编码或名称', form);
      nextTick(() => {
        searchEvent(form.searchName, ['nodeName', searchedFields.value.length ? '1' : '0']);
      });
    }
  },
  {
    name: '材料类别或牌号',
    field: 'materialType',
    type: 'input',
    onSearchFormChange: (form: any) => {
      console.log('onSearchFormChange 材料类别或牌号', form);
      nextTick(() => {
        searchEvent(form.materialType, ['nodeName', searchedFields.value.length ? '1' : '0']);
      });
    }
  }
];
const nodeNameFilterOptions = ref([{ data: '', name: 'nodeName' }]);
const searchText = computed(() => {
  return {
    searchName: String(searchForm.searchName).trim().toLowerCase(),
    materialType: String(searchForm.materialType).trim().toLowerCase()
  };
});

const isFilter = computed(() => {
  return !!searchedFields.value?.length;
});
const searchedFields = computed(() => {
  let res: string[] = [];
  if (String(searchForm.searchName).trim().toLowerCase()) {
    res.push('nodeName');
    res.push('nodeCode');
  }
  if (String(searchForm.materialType).trim().toLowerCase()) {
    res.push('materialType');
    res.push('materialFlag');
  }
  return res;
});
const filterAgeMethod: any = ({ row }: any) => {
  return searchedFields.value.some(key => {
    let searchNameFilterRes = !searchText.value.searchName;
    if (
      searchText.value.searchName &&
      String(row[key]).toLowerCase().indexOf(searchText.value.searchName) > -1
    ) {
      searchNameFilterRes = true;
      console.log('row', row);
    }
    let materialTypeFilterRes = !searchText.value.materialType;
    if (
      searchText.value.materialType &&
      String(row[key]).toLowerCase().indexOf(searchText.value.materialType) > -1
    ) {
      materialTypeFilterRes = true;
    }
    if (searchNameFilterRes && materialTypeFilterRes) {
      row.filtered = true;
    } else {
      row.filtered = false;
    }
    return searchNameFilterRes && materialTypeFilterRes;
  });
};
const tableFieldsSetting: TableFieldsSettingType[] = [
  {
    title: '材料类别',
    field: 'materialType',
    minWidth: 150,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '材料牌号',
    field: 'materialFlag',
    minWidth: 150,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '数量',
    field: 'quantity',
    minWidth: 80,
    align: 'right',
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '单位用量',
    field: 'dosage',
    slot: 'dosageSlot',
    align: 'right',
    minWidth: 100,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '供应商名称/供应商ID',
    field: 'supplier',
    slot: 'supplierSlot',
    minWidth: 150,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '版本',
    field: 'version',
    minWidth: 80,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '同步状态',
    field: 'desc',
    fixed: 'right',
    slot: 'syncStatusSlot',
    align: 'center',
    minWidth: 100,
    columnSettingConfig: {
      enabled: true
    }
  },
  {
    title: '操作',
    field: 'op',
    fixed: 'right',
    slot: 'op',
    align: 'center',
    minWidth: 80,
    columnSettingConfig: {
      enabled: true,
      type: 'FIXED'
    }
  }
];

const renderTag = (status: string) => {
  switch (status) {
    case BomSyncStatusEnum.SYNC_EXCEPTION:
      return 'danger';
    case BomSyncStatusEnum.SYNCING:
      return 'primary';
    case BomSyncStatusEnum.SYNCED:
    default:
      return 'success';
  }
};

/**
 * 同步操作
 */
function handleSyncFirstPart(row: GetBomProductTreeResult) {
  createConfirm('提示', '同步数据会覆盖历史数据，请确认是否继续同步？', {
    iconType: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await postSyncFirstPart(productNo, row.nodeNo);
      createMessage.success('操作成功！');
      loading.value = false;
      refresh();
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}

const tableConfig = reactive({
  treeConfig: {
    transform: true,
    rowField: 'nodeNo',
    parentField: 'parentNodeNo',
    iconOpen: 'c-mian-xia iconfont',
    iconClose: 'c-mian-you iconfont',
    lazy: true,
    hasChild: 'hasChildren',
    loadMethod({ row }) {
      // 异步加载子节点
      return getBomProductTree(productNo, row.nodeNo);
    }
  } as VxeTablePropTypes.TreeConfig
});
const totalCount = ref(0);
/**
 * 加载数据
 */
function loadData() {
  return getBomProductTree(productNo, '-1').then(res => {
    totalCount.value = res.length || 0;
    return {
      records: res,
      total: res.length
    };
  });
}
const options: CPageTableProps = {
  title: title,
  searchOptions,
  isDetailPage: false,
  tableOptions: {
    pagination: false,
    loadData,
    border: true,
    extraTableOption: {
      treeConfig: tableConfig.treeConfig,
      scrollY: { enabled: true },
      maxHeight: '100%',
      rowConfig: { height: 56 }
    },
    rowKey: 'nodeNo',
    cellHeightSize: 'small'
  },
  tableFieldsSetting,
  enableFieldsSetting: true
};
const searchForm = reactive({
  searchName: '',
  materialType: ''
});
const [registerPage, { refresh, searchEvent }] = useCPageTable(options);
</script>
<style lang="scss" scoped>
.product-bom-drawer-page-table {
  :deep(.c-page-table__body) {
    height: calc(100vh - 50px - 40px - 56px - 32px);
    overflow-y: auto;
    overflow-x: hidden;
    .c-page-table__body-main {
      height: 100%;
    }
    .body-main__filter {
      padding: 16px 16px 12px;
      min-height: 60px;
      .filter-fixed-buttons {
        bottom: 12px;
      }
    }
    .body-main__table {
      padding: 0 16px;
      height: calc(100% - 60px);
      .vxe-tree--btn-wrapper {
        top: 10px;
        .vxe-tree--node-btn {
          color: #435970 !important;
        }
      }
      .vxe-cell--filter {
        display: none;
      }
    }
  }
}
</style>
